﻿using UnityEngine;

namespace Core
{
    /// <summary>
    /// 前缀 img_XXX
    /// </summary>
    public class UIImage : UIWidget
    {
        private UnityEngine.UI.Image img;

        public bool raycastTarget
        {
            get => img.raycastTarget;
            set => img.raycastTarget = value;
        }

        public Color color
        {
            get => img.color;
            set => img.color = value;
        }

        public float fillAmount
        {
            get => img.fillAmount;
            set => img.fillAmount = Mathf.Clamp01(value);
        }

        public Sprite sprite
        {
            get => img.sprite;
            set => img.sprite = value;
        }

        public void SetAlpha(float alpha)
        {
            alpha = Mathf.Clamp01(alpha);
            var c = color;
            c.a = alpha;
            color = c;
        }

        public void SetNativeSize()
        {
            img.SetNativeSize();
        }

        public RectTransform rect { get; private set; }
        public UnityEngine.UI.Image.Type type { get; private set; }

        private ISlice spriteSlice;

        private Material originalMat;
        private Material grayMat;
        private bool isGray;
        //private Material blackMat;

        public override void Awake(GameObject go)
        {
            base.Awake(go);

            img = go.GetComponent<UnityEngine.UI.Image>();
            originalMat = img.material;

            type = img.type;

            rect = img.rectTransform;

            spriteSlice = go.GetComponent<ISlice>();

            raycastTarget = false;
            isGray = false;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            img = null;
        }

        public void SetGray(bool gray)
        {
            if (isGray == gray) return;

            isGray = gray;

            if (gray == false)
            {
                img.material = originalMat;
            }
            else
            {
                var asset = S.Res.LoadSync("Res/Shader/Sprites_DefaultGray.mat");
                grayMat = asset.Obj as Material;
                img.material = grayMat;
            }
        }

        public void Switch(int i)
        {
            spriteSlice?.Switch(i);
        }
    }
}
